// 连接到Socket.IO服务器
const socket = io({
  transports: ['websocket', 'polling'],
  timeout: 20000,
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  randomizationFactor: 0.5,
  upgrade: true,
  forceNew: true,
  rejectUnauthorized: false
});

// 获取DOM元素
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');
const updateConfigBtn = document.getElementById('updateConfigBtn');
const autoFillBtn = document.getElementById('autoFillBtn');
const timeStepInput = document.getElementById('timeStep');
const macroEventProbabilityInput = document.getElementById('macroEventProbability');
const investorEntryRateInput = document.getElementById('investorEntryRate');

// 止盈止损配置元素
const takeProfitProbabilityInput = document.getElementById('takeProfitProbability');
const stopLossProbabilityInput = document.getElementById('stopLossProbability');
const takeProfitThresholdInput = document.getElementById('takeProfitThreshold');
const stopLossThresholdInput = document.getElementById('stopLossThreshold');

// 投资者权重配置元素
const retailWeightInput = document.getElementById('retailWeight');
const marketMakerWeightInput = document.getElementById('marketMakerWeight');
const institutionalWeightInput = document.getElementById('institutionalWeight');

// 策略分布配置元素
const retailRandomWeightInput = document.getElementById('retailRandomWeight');
const retailTrendWeightInput = document.getElementById('retailTrendWeight');
const retailMeanWeightInput = document.getElementById('retailMeanWeight');
const retailGamblerWeightInput = document.getElementById('retailGamblerWeight');
const retailHerdWeightInput = document.getElementById('retailHerdWeight'); // 新增
const institutionalTrendWeightInput = document.getElementById('institutionalTrendWeight');
const institutionalMeanWeightInput = document.getElementById('institutionalMeanWeight');

// 初始投资者人数配置元素
const initialRetailCountInput = document.getElementById('initialRetailCount');
const initialMarketMakerCountInput = document.getElementById('initialMarketMakerCount');
const initialInstitutionalCountInput = document.getElementById('initialInstitutionalCount');

// 初始资本配置元素
const retailCapitalInput = document.getElementById('retailCapital');
const marketMakerCapitalInput = document.getElementById('marketMakerCapital');
const institutionalCapitalInput = document.getElementById('institutionalCapital');

// 资产配置元素
const aaplInitialPriceInput = document.getElementById('aaplInitialPrice');
const aaplTotalSharesInput = document.getElementById('aaplTotalShares');
const aaplInstitutionalCapitalInput = document.getElementById('aaplInstitutionalCapital');
const aaplInstitutionalSharesInput = document.getElementById('aaplInstitutionalShares');

const googInitialPriceInput = document.getElementById('googInitialPrice');
const googTotalSharesInput = document.getElementById('googTotalShares');
const googInstitutionalCapitalInput = document.getElementById('googInstitutionalCapital');
const googInstitutionalSharesInput = document.getElementById('googInstitutionalShares');

const timeElement = document.getElementById('time');
const totalInvestorsElement = document.getElementById('totalInvestors');
const bankruptInvestorsElement = document.getElementById('bankruptInvestors');
const totalAssetsElement = document.getElementById('totalAssets');
const assetsContainer = document.getElementById('assetsContainer');
const investorsContainer = document.getElementById('investorsContainer');
const eventsContainer = document.getElementById('eventsContainer');

// 图表实例
let aaplChart = null;
let googChart = null;
let buyVolumeChart = null;
let sellVolumeChart = null;
let orderBookChart = null; // 新增订单簿图表

// 添加事件监听器
startBtn.addEventListener('click', () => {
    socket.emit('startSimulation');
    toggleControlButtons(true);
});

resetBtn.addEventListener('click', () => {
    socket.emit('resetMarket');
});

stopBtn.addEventListener('click', () => {
    socket.emit('stopSimulation');
    toggleControlButtons(false);
});

updateConfigBtn.addEventListener('click', () => {
    const config = {
        timeStep: parseInt(timeStepInput.value),
        macroEventProbability: parseFloat(macroEventProbabilityInput.value),
        investorGeneratorConfig: {
            entryRate: parseFloat(investorEntryRateInput.value),
            investorTypes: [
                { type: 'RetailInvestor', weight: parseFloat(retailWeightInput.value) },
                { type: 'MarketMaker', weight: parseFloat(marketMakerWeightInput.value) },
                { type: 'InstitutionalInvestor', weight: parseFloat(institutionalWeightInput.value) }
            ],
            strategyDistribution: {
                RetailInvestor: [
                    { strategy: 'RandomStrategy', weight: parseFloat(retailRandomWeightInput.value) },
                    { strategy: 'TrendFollowingStrategy', weight: parseFloat(retailTrendWeightInput.value) },
                    { strategy: 'MeanReversionStrategy', weight: parseFloat(retailMeanWeightInput.value) },
                    { strategy: 'GamblerStrategy', weight: parseFloat(retailGamblerWeightInput.value) },
                    { strategy: 'HerdBehaviorStrategy', weight: parseFloat(retailHerdWeightInput.value) } // 新增
                ],
                MarketMaker: [
                    { strategy: 'RandomStrategy', weight: 1.0 }
                ],
                InstitutionalInvestor: [
                    { strategy: 'TrendFollowingStrategy', weight: parseFloat(institutionalTrendWeightInput.value) },
                    { strategy: 'MeanReversionStrategy', weight: parseFloat(institutionalMeanWeightInput.value) }
                ]
            }
        },
        initialInvestorCounts: {
            retail: parseInt(initialRetailCountInput.value),
            marketMaker: parseInt(initialMarketMakerCountInput.value),
            institutional: parseInt(initialInstitutionalCountInput.value)
        },
        initialCapitals: {
            retail: parseInt(retailCapitalInput.value),
            marketMaker: parseInt(marketMakerCapitalInput.value),
            institutional: parseInt(institutionalCapitalInput.value)
        },
        // 资产配置
        assetConfig: {
            AAPL: {
                initialPrice: parseFloat(aaplInitialPriceInput.value),
                totalShares: parseInt(aaplTotalSharesInput.value),
                institutionalCapital: parseInt(aaplInstitutionalCapitalInput.value),
                institutionalShares: parseInt(aaplInstitutionalSharesInput.value)
            },
            GOOG: {
                initialPrice: parseFloat(googInitialPriceInput.value),
                totalShares: parseInt(googTotalSharesInput.value),
                institutionalCapital: parseInt(googInstitutionalCapitalInput.value),
                institutionalShares: parseInt(googInstitutionalSharesInput.value)
            }
        },
        // 止盈止损配置
        takeProfitProbability: parseFloat(takeProfitProbabilityInput.value),
        stopLossProbability: parseFloat(stopLossProbabilityInput.value),
        takeProfitThreshold: parseFloat(takeProfitThresholdInput.value),
        stopLossThreshold: parseFloat(stopLossThresholdInput.value)
    };
    socket.emit('updateConfig', config);
});

// 自动填充推荐值
autoFillBtn.addEventListener('click', () => {
    // 获取散户和做市商的资本总和作为推荐值
    const retailCapital = parseInt(retailCapitalInput.value) * parseInt(initialRetailCountInput.value);
    const marketMakerCapital = parseInt(marketMakerCapitalInput.value) * parseInt(initialMarketMakerCountInput.value);
    const totalCapital = retailCapital + marketMakerCapital;
    
    // 为AAPL设置推荐值
    aaplInstitutionalCapitalInput.value = totalCapital * 2; // 控股机构资本为其他投资者总和的2倍
    aaplInstitutionalSharesInput.value = aaplTotalSharesInput.value; // 控股机构持有全部股份
    
    // 为GOOG设置推荐值
    googInstitutionalCapitalInput.value = totalCapital * 2; // 控股机构资本为其他投资者总和的2倍
    googInstitutionalSharesInput.value = googTotalSharesInput.value; // 控股机构持有全部股份
});

// 处理连接错误
socket.on('connect_error', (error) => {
    console.error('连接服务器失败:', error.message);
    console.log('错误详情:', error);
});

// 处理连接超时
socket.on('connect_timeout', (timeout) => {
    console.error('连接服务器超时:', timeout);
});

// 处理断开连接
socket.on('disconnect', (reason) => {
    console.error('与服务器断开连接:', reason);
    if (reason === 'io server disconnect') {
        // 服务器主动断开连接，尝试重新连接
        socket.connect();
    }
});

// 处理重新连接尝试
socket.on('reconnect_attempt', (attemptNumber) => {
    console.log('尝试重新连接:', attemptNumber);
});

// 处理重新连接成功
socket.on('reconnect', (attemptNumber) => {
    console.log('重新连接成功，尝试次数:', attemptNumber);
});

// 处理重新连接失败
socket.on('reconnect_failed', () => {
    console.error('重新连接失败');
});

// 处理市场更新
socket.on('marketUpdate', (data) => {
    updateMarketInfo(data);
    updateAssets(data.assets);
    updateInvestors(data.investors);
    updateEvents(data.activeEvents);
    updateCharts(data.assets);
    updateVolumeCharts(data.tradeData);
    updateOrderBookCharts(data.orderBooks); // 更新订单簿图表
});

// 处理市场重置
socket.on('marketReset', () => {
    // 清空所有显示内容
    timeElement.textContent = '0';
    totalInvestorsElement.textContent = '0';
    bankruptInvestorsElement.textContent = '0';
    totalAssetsElement.textContent = '0';
    assetsContainer.innerHTML = '';
    investorsContainer.innerHTML = '';
    eventsContainer.innerHTML = '<p>当前无活跃宏观事件</p>';
    
    // 重置图表
    if (aaplChart) aaplChart.destroy();
    if (googChart) googChart.destroy();
    if (buyVolumeChart) buyVolumeChart.destroy();
    if (sellVolumeChart) sellVolumeChart.destroy();
    if (orderBookChart) orderBookChart.destroy(); // 销毁订单簿图表
    
    aaplChart = null;
    googChart = null;
    buyVolumeChart = null;
    sellVolumeChart = null;
    orderBookChart = null; // 重置订单簿图表
    
    toggleControlButtons(false);
});

// 更新市场基本信息
function updateMarketInfo(data) {
    timeElement.textContent = data.time;
    totalInvestorsElement.textContent = Object.keys(data.investors).length;
    bankruptInvestorsElement.textContent = data.bankruptInvestorCount || 0;
    totalAssetsElement.textContent = Object.keys(data.assets).length;
}

// 更新资产信息
function updateAssets(assets) {
    assetsContainer.innerHTML = '';
    
    for (const assetId in assets) {
        const asset = assets[assetId];
        const assetElement = document.createElement('div');
        assetElement.className = 'asset-card';
        
        assetElement.innerHTML = `
            <h3>${asset.name} (${assetId})</h3>
            <p>当前价格: ¥${asset.price.toFixed(2)}</p>
            <div class="price-history">
                <canvas id="priceChart-${assetId}" width="200" height="100"></canvas>
            </div>
        `;
        
        assetsContainer.appendChild(assetElement);
    }
}

// 更新投资者统计
function updateInvestors(investors) {
    investorsContainer.innerHTML = '';
    
    // 统计各类投资者
    const investorStats = {};
    for (const investorId in investors) {
        const investor = investors[investorId];
        if (!investorStats[investor.type]) {
            investorStats[investor.type] = { count: 0, totalValue: 0 };
        }
        investorStats[investor.type].count++;
        investorStats[investor.type].totalValue += investor.totalValue;
    }
    
    // 显示统计信息
    for (const type in investorStats) {
        const stats = investorStats[type];
        const investorElement = document.createElement('div');
        investorElement.className = `investor-card investor-${type.toLowerCase()}`;
        
        investorElement.innerHTML = `
            <h3>${getTypeDisplayName(type)}</h3>
            <p>人数: ${stats.count}</p>
            <p>总价值: ¥${stats.totalValue.toFixed(2)}</p>
        `;
        
        investorsContainer.appendChild(investorElement);
    }
}

// 更新宏观事件信息
function updateEvents(events) {
    eventsContainer.innerHTML = '';
    
    if (events.length === 0) {
        eventsContainer.innerHTML = '<p>当前无活跃宏观事件</p>';
        return;
    }
    
    events.forEach(event => {
        const eventElement = document.createElement('div');
        eventElement.className = `event-card event-${event.type.toLowerCase()}`;
        
        eventElement.innerHTML = `
            <h3>${event.name}</h3>
            <p>类型: ${event.type}</p>
            <p>影响: ${event.impact > 0 ? '+' : ''}${event.impact}</p>
            <p>剩余时间: ${event.remainingDuration}</p>
        `;
        
        eventsContainer.appendChild(eventElement);
    });
}

// 更新K线图
function updateCharts(assets) {
    for (const assetId in assets) {
        const asset = assets[assetId];
        
        // 获取历史数据
        fetch(`/api/assets/${assetId}/history`)
            .then(response => response.json())
            .then(data => {
                if (assetId === 'AAPL') {
                    updateKlineChart('aaplChart', data, 'Apple Inc. (AAPL)');
                } else if (assetId === 'GOOG') {
                    updateKlineChart('googChart', data, 'Alphabet Inc. (GOOG)');
                }
            })
            .catch(error => console.error('获取图表数据失败:', error));
    }
}

// 更新K线图
function updateKlineChart(canvasId, data, title) {
    const ctx = document.getElementById(canvasId).getContext('2d');
    
    // 准备K线图数据（蜡烛图）
    const chartData = {
        datasets: [{
            label: title,
            data: data.map(d => ({
                x: d.time,
                o: d.open,
                h: d.high,
                l: d.low,
                c: d.close
            })),
            type: 'candlestick',
            borderColor: function(context) {
                // 根据开盘价和收盘价决定边框颜色
                const dataPoint = context.dataset.data[context.dataIndex];
                return dataPoint.c >= dataPoint.o ? '#27ae60' : '#e74c3c';
            },
            backgroundColor: function(context) {
                // 根据开盘价和收盘价决定背景颜色
                const dataPoint = context.dataset.data[context.dataIndex];
                return dataPoint.c >= dataPoint.o ? 'rgba(39, 174, 96, 0.7)' : 'rgba(231, 76, 60, 0.7)';
            },
            borderWidth: 1,
        }]
    };
    
    // 如果图表已存在，更新数据
    if (canvasId === 'aaplChart' && aaplChart) {
        aaplChart.data.datasets = chartData.datasets;
        aaplChart.update();
        return;
    }
    
    if (canvasId === 'googChart' && googChart) {
        googChart.data.datasets = chartData.datasets;
        googChart.update();
        return;
    }
    
    // 创建新图表
    const config = {
        type: 'candlestick',
        data: chartData,
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: title
                },
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    type: 'linear',
                    display: true,
                    title: {
                        display: true,
                        text: '时间'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: '价格'
                    }
                }
            }
        }
    };
    
    if (canvasId === 'aaplChart') {
        if (aaplChart) aaplChart.destroy();
        aaplChart = new Chart(ctx, config);
    } else if (canvasId === 'googChart') {
        if (googChart) googChart.destroy();
        googChart = new Chart(ctx, config);
    }
}

// 更新交易量图表
function updateVolumeCharts(tradeData) {
    if (!tradeData) return;
    
    const assets = Object.keys(tradeData);
    const buyVolumes = assets.map(asset => tradeData[asset].buyVolume);
    const sellVolumes = assets.map(asset => tradeData[asset].sellVolume);
    
    updateVolumeChart('buyVolumeChart', assets, buyVolumes, '买入量', '#27ae60');
    updateVolumeChart('sellVolumeChart', assets, sellVolumes, '卖出量', '#e74c3c');
}

// 更新单个交易量图表
function updateVolumeChart(canvasId, labels, data, title, color) {
    const ctx = document.getElementById(canvasId).getContext('2d');
    
    const chartData = {
        labels: labels,
        datasets: [{
            label: title,
            data: data,
            backgroundColor: color,
            borderColor: color,
            borderWidth: 1
        }]
    };
    
    // 如果图表已存在，更新数据
    if (canvasId === 'buyVolumeChart' && buyVolumeChart) {
        buyVolumeChart.data = chartData;
        buyVolumeChart.update();
        return;
    }
    
    if (canvasId === 'sellVolumeChart' && sellVolumeChart) {
        sellVolumeChart.data = chartData;
        sellVolumeChart.update();
        return;
    }
    
    // 创建新图表
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: title
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    };
    
    if (canvasId === 'buyVolumeChart') {
        if (buyVolumeChart) buyVolumeChart.destroy();
        buyVolumeChart = new Chart(ctx, config);
    } else if (canvasId === 'sellVolumeChart') {
        if (sellVolumeChart) sellVolumeChart.destroy();
        sellVolumeChart = new Chart(ctx, config);
    }
}

// 更新订单簿图表（新增功能）
function updateOrderBookCharts(orderBooks) {
    // 创建订单簿图表容器（如果不存在）
    let orderBookChartContainer = document.getElementById('orderBookChartContainer');
    if (!orderBookChartContainer) {
        const volumeHeatmapSection = document.querySelector('.volume-heatmap');
        if (volumeHeatmapSection) {
            orderBookChartContainer = document.createElement('div');
            orderBookChartContainer.id = 'orderBookChartContainer';
            orderBookChartContainer.className = 'orderbook-chart-container';
            orderBookChartContainer.innerHTML = `
                <h2>订单簿图表</h2>
                <div class="orderbook-chart-wrapper">
                    <canvas id="orderBookChart"></canvas>
                </div>
            `;
            volumeHeatmapSection.parentNode.insertBefore(orderBookChartContainer, volumeHeatmapSection.nextSibling);
        }
    }
    
    // 收集所有资产的订单簿数据
    updateAllAssetsOrderBookChart(orderBooks);
}

// 更新所有资产的订单簿图表（新增功能）
function updateAllAssetsOrderBookChart(orderBooks) {
    const canvasId = 'orderBookChart';
    const ctx = document.getElementById(canvasId)?.getContext('2d');
    
    if (!ctx) return;
    
    // 准备所有资产的订单簿数据
    const allPrices = new Set();
    const allBuyData = [];
    const allSellData = [];
    const assetLabels = [];
    
    // 收集所有资产的数据
    for (const assetId in orderBooks) {
        const orderBook = orderBooks[assetId];
        assetLabels.push(assetId);
        
        // 收集价格点
        orderBook.buyOrders.forEach(order => allPrices.add(order.price));
        orderBook.sellOrders.forEach(order => allPrices.add(order.price));
    }
    
    // 按价格排序
    const sortedPrices = Array.from(allPrices).sort((a, b) => a - b);
    
    // 为每个资产准备数据
    for (const assetId in orderBooks) {
        const orderBook = orderBooks[assetId];
        const buyMap = new Map();
        const sellMap = new Map();
        
        // 收集买单数据
        orderBook.buyOrders.forEach(order => {
            if (buyMap.has(order.price)) {
                buyMap.set(order.price, buyMap.get(order.price) + order.quantity);
            } else {
                buyMap.set(order.price, order.quantity);
            }
        });
        
        // 收集卖单数据
        orderBook.sellOrders.forEach(order => {
            if (sellMap.has(order.price)) {
                sellMap.set(order.price, sellMap.get(order.price) + order.quantity);
            } else {
                sellMap.set(order.price, order.quantity);
            }
        });
        
        // 准备图表数据
        const buyData = sortedPrices.map(price => buyMap.get(price) || 0);
        const sellData = sortedPrices.map(price => sellMap.get(price) || 0);
        
        allBuyData.push(buyData);
        allSellData.push(sellData);
    }
    
    // 准备图表数据
    const chartData = {
        labels: sortedPrices.map(price => `¥${price.toFixed(2)}`),
        datasets: []
    };
    
    // 为每个资产添加买入数据集
    assetLabels.forEach((assetId, index) => {
        chartData.datasets.push({
            label: `${assetId} 买入量`,
            data: allBuyData[index],
            backgroundColor: getAssetColor(index, 'buy'),
            borderColor: getAssetColor(index, 'buy'),
            borderWidth: 1,
            xAxisID: 'x-left'
        });
        
        chartData.datasets.push({
            label: `${assetId} 卖出量`,
            data: allSellData[index],
            backgroundColor: getAssetColor(index, 'sell'),
            borderColor: getAssetColor(index, 'sell'),
            borderWidth: 1,
            xAxisID: 'x-right'
        });
    });
    
    // 如果图表已存在，更新数据
    if (orderBookChart) {
        orderBookChart.data = chartData;
        orderBookChart.update();
        return;
    }
    
    // 创建新图表
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            indexAxis: 'y',
            plugins: {
                title: {
                    display: true,
                    text: '订单簿'
                },
                legend: {
                    display: true
                }
            },
            scales: {
                x: {
                    display: false
                },
                'x-left': {
                    position: 'top',
                    title: {
                        display: true,
                        text: '买入量'
                    }
                },
                'x-right': {
                    position: 'bottom',
                    title: {
                        display: true,
                        text: '卖出量'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '价格'
                    }
                }
            }
        }
    };
    
    if (orderBookChart) orderBookChart.destroy();
    orderBookChart = new Chart(ctx, config);
}

// 获取资产颜色
function getAssetColor(index, type) {
    const colors = {
        buy: ['rgba(39, 174, 96, 0.7)', 'rgba(46, 204, 113, 0.7)', 'rgba(52, 235, 138, 0.7)'],
        sell: ['rgba(231, 76, 60, 0.7)', 'rgba(240, 84, 84, 0.7)', 'rgba(255, 99, 99, 0.7)']
    };
    
    return colors[type][index % colors[type].length];
}

// 获取投资者类型显示名称
function getTypeDisplayName(type) {
    switch (type) {
        case 'RetailInvestor':
            return '散户投资者';
        case 'MarketMaker':
            return '做市商';
        case 'InstitutionalInvestor':
            return '机构投资者';
        default:
            return type;
    }
}

// 切换控制按钮状态
function toggleControlButtons(running) {
    startBtn.disabled = running;
    stopBtn.disabled = !running;
    resetBtn.disabled = running;
}

// 初始化按钮状态
toggleControlButtons(false);

// 获取初始配置
fetch('/api/config')
    .then(response => response.json())
    .then(config => {
        timeStepInput.value = config.timeStep;
        macroEventProbabilityInput.value = config.macroEventProbability;
        investorEntryRateInput.value = config.investorGeneratorConfig.entryRate;
        
        // 设置止盈止损配置
        if (config.takeProfitProbability !== undefined) {
            takeProfitProbabilityInput.value = config.takeProfitProbability;
        }
        if (config.stopLossProbability !== undefined) {
            stopLossProbabilityInput.value = config.stopLossProbability;
        }
        if (config.takeProfitThreshold !== undefined) {
            takeProfitThresholdInput.value = config.takeProfitThreshold;
        }
        if (config.stopLossThreshold !== undefined) {
            stopLossThresholdInput.value = config.stopLossThreshold;
        }
        
        // 设置投资者权重
        const investorTypes = config.investorGeneratorConfig.investorTypes;
        investorTypes.forEach(type => {
            switch (type.type) {
                case 'RetailInvestor':
                    retailWeightInput.value = type.weight;
                    break;
                case 'MarketMaker':
                    marketMakerWeightInput.value = type.weight;
                    break;
                case 'InstitutionalInvestor':
                    institutionalWeightInput.value = type.weight;
                    break;
            }
        });
        
        // 设置策略分布
        const strategyDistribution = config.investorGeneratorConfig.strategyDistribution;
        if (strategyDistribution) {
            const retailStrategies = strategyDistribution.RetailInvestor || [];
            retailStrategies.forEach(strategy => {
                switch (strategy.strategy) {
                    case 'RandomStrategy':
                        retailRandomWeightInput.value = strategy.weight;
                        break;
                    case 'TrendFollowingStrategy':
                        retailTrendWeightInput.value = strategy.weight;
                        break;
                    case 'MeanReversionStrategy':
                        retailMeanWeightInput.value = strategy.weight;
                        break;
                    case 'GamblerStrategy':
                        retailGamblerWeightInput.value = strategy.weight;
                        break;
                    case 'HerdBehaviorStrategy':
                        retailHerdWeightInput.value = strategy.weight || 0.0;
                        break;
                }
            });
            
            const institutionalStrategies = strategyDistribution.InstitutionalInvestor || [];
            institutionalStrategies.forEach(strategy => {
                switch (strategy.strategy) {
                    case 'TrendFollowingStrategy':
                        institutionalTrendWeightInput.value = strategy.weight;
                        break;
                    case 'MeanReversionStrategy':
                        institutionalMeanWeightInput.value = strategy.weight;
                        break;
                }
            });
        }
        
        // 设置初始投资者人数
        if (config.initialInvestorCounts) {
            initialRetailCountInput.value = config.initialInvestorCounts.retail || 2;
            initialMarketMakerCountInput.value = config.initialInvestorCounts.marketMaker || 1;
            initialInstitutionalCountInput.value = config.initialInvestorCounts.institutional || 1;
        }
        
        // 设置初始资本
        if (config.initialCapitals) {
            retailCapitalInput.value = config.initialCapitals.retail || 50000;
            marketMakerCapitalInput.value = config.initialCapitals.marketMaker || 1000000;
            institutionalCapitalInput.value = config.initialCapitals.institutional || 10000000;
        }
        
        // 设置资产配置
        if (config.assetConfig) {
            if (config.assetConfig.AAPL) {
                aaplInitialPriceInput.value = config.assetConfig.AAPL.initialPrice || 150.00;
                aaplTotalSharesInput.value = config.assetConfig.AAPL.totalShares || 1000000;
                aaplInstitutionalCapitalInput.value = config.assetConfig.AAPL.institutionalCapital || 10000000;
                aaplInstitutionalSharesInput.value = config.assetConfig.AAPL.institutionalShares || 1000000;
            }
            
            if (config.assetConfig.GOOG) {
                googInitialPriceInput.value = config.assetConfig.GOOG.initialPrice || 2500.00;
                googTotalSharesInput.value = config.assetConfig.GOOG.totalShares || 1000000;
                googInstitutionalCapitalInput.value = config.assetConfig.GOOG.institutionalCapital || 10000000;
                googInstitutionalSharesInput.value = config.assetConfig.GOOG.institutionalShares || 1000000;
            }
        }
    })
    .catch(error => console.error('获取配置失败:', error));